import axios from 'axios'
import {logout} from "./login";


const instance = axios.create({
    baseURL: 'http://localhost:40081',
    timeout: 2000,
    headers: {'X-Custom-Header': 'foobar'}
})

//请求响应拦截器 config是要返回的数据
instance.interceptors.request.use(config => {
    const token = localStorage.getItem('token') || sessionStorage.getItem('token');
    console.log('request token:', token)
    if (token && token !== 'null') {
        console.log('request token:', token)
        config.headers.Authorization = token;
    }
    console.log('request data:', config)
    return config
}, error => {
    console.log('request error:', error)
    return error
})


instance.interceptors.response.use(res => {
    // 如果登录已经过期 那么就登出 并且清除本地token
    if (res.data.code === 401) {
        console.log('登录状态已经失效，需要重新登录')
        logout().then(r => {
            // 清除本地的token
            sessionStorage.removeItem('token')
            localStorage.removeItem('token')
        })
    }
    return res;
}, error => {
    console.log('response error:', error)
    return error
})

export default instance
